/*
 * @Description: xxx描述文件内容
 * @Autor: gufuyan
 * @Date: 2021-11-26 08:50:50
 * @lastModifiedBy: gufuyan
 * @LastEditTime: 2021-11-29 10:31:19
 * @lastModifiedContent: xxx描述修改的内容
 */
import React, { useEffect, useState } from 'react';
import { Input, Button, message, Modal, Radio, Tree, Empty, Form, Space, Select, Spin } from 'antd';
import {
  DownOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import { history } from 'umi';
import { deleteForm, addForm, updateForm } from './service';
import styles from './index.less';

interface IConfigForm {
  data: any;
  refresh: () => void;
}

const ConfigForm: React.FC<IConfigForm> = (props) => {
  const [form] = Form.useForm();
  const [treeData, setTreeData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [firstLevel, setFirstLevel] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);

  const [level, setLevel] = useState('');
  const [type, setType] = useState('');
  const [id, setId] = useState(0);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const edit = (type, parent, item) => {
    setType('edit');
    setLevel(type);
    if (type === 'type') {
      setId(parent.key);
      form.setFieldsValue({
        directoryLevel: type,
        categoryName: parent.oldTitle,
      });
    }

    if (type === 'form') {
      setId(item.key);
      form.setFieldsValue({
        directoryLevel: type,
        category: parent.key,
        formName: item.oldTitle,
        iconUrl: item.url,
      });
    }
    setAddVisible(true);
  };

  useEffect(() => {
    let tree = props.data;
    tree = JSON.stringify(tree);
    tree = tree.replaceAll(/name/g, 'title');
    tree = tree.replaceAll(/id/g, 'key');
    tree = tree.replaceAll(/list/g, 'children');
    tree = JSON.parse(tree);

    const firstLevelData = [];
    tree.forEach((el) => {
      firstLevelData.push({
        label: el.title,
        value: el.key,
      });
    });
    setFirstLevel(firstLevelData);

    tree.forEach((type) => {
      if (type.url) type.icon = <img src={type.url} style={{ width: '70%' }} />;
      type.oldTitle = type.title;
      type.title = (
        <span>
          <label className={styles.label}>{type.title}</label>
          <Space className={styles.space} size={20}>
            <EditOutlined style={{ color: '#1890ff' }} onClick={() => edit('type', type, null)} />
            <DeleteOutlined
              style={{ color: 'red' }}
              onClick={() => {
                setLoading(true);
                deleteForm(type.key).then(() => {
                  message.success('删除成功！');
                  setAddVisible(false);
                  setLoading(false);
                  setTimeout(() => {
                    props.refresh();
                  }, 500);
                });
              }}
            />
          </Space>
        </span>
      );
      //表单
      if (type.children) {
        type.children.forEach((el) => {
          if (el.url) el.icon = <img src={el.url} style={{ width: '70%' }} />;
          el.oldTitle = el.title;
          el.title = (
            <span>
              <label className={styles.label}>{el.title}</label>
              <Space className={styles.space} size={20}>
                <SettingOutlined
                  className={styles.setting}
                  onClick={() => {
                    history.push(`/drag?id=${el.key}&name=${el.oldTitle}`);
                  }}
                />
                <EditOutlined style={{ color: '#1890ff' }} onClick={() => edit('form', type, el)} />
                <DeleteOutlined
                  style={{ color: 'red' }}
                  onClick={() => {
                    setLoading(true);
                    deleteForm(el.key).then(() => {
                      message.success('删除成功！');
                      setAddVisible(false);
                      setLoading(false);
                      setTimeout(() => {
                        props.refresh();
                      }, 500);
                    });
                  }}
                />
              </Space>
            </span>
          );
        });
      }
    });

    setTreeData(tree);
  }, [props.data]);

  return (
    <>
      <Button type="primary" onClick={showModal} className={styles.configForm}>
        表单配置
      </Button>
      <Modal
        title="表单配置"
        width={600}
        visible={isModalVisible}
        footer={null}
        onCancel={handleCancel}
        className={styles.configList}
      >
        <Button
          icon={<PlusOutlined />}
          onClick={() => {
            setAddVisible(true);
            setType('add');
          }}
          className={styles.addBtn}
        >
          新增
        </Button>
        {loading && (
          <div className={styles.addLoading}>
            <Spin />
          </div>
        )}
        {treeData.length > 0 ? (
          <Tree
            showIcon
            defaultExpandAll
            defaultSelectedKeys={['0-0-0']}
            switcherIcon={<DownOutlined />}
            treeData={treeData}
            className={styles.formColumn}
          />
        ) : (
          <Empty />
        )}
      </Modal>
      <Modal
        title={type === 'add' ? '新增' : '修改'}
        width={500}
        visible={addVisible}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              const params = {
                type: values.directoryLevel,
              };
              if (values.directoryLevel === 'form') {
                params.name = values.formName;
                params.parentId = values.category;
                params.url = values.iconUrl;
              }
              if (values.directoryLevel === 'type') {
                params.name = values.categoryName;
              }
              setLoading(true);
              if (type === 'add') {
                addForm(params).then(() => {
                  message.success('新增成功！');
                  props.refresh();
                  setAddVisible(false);
                  setIsModalVisible(false);
                  setLoading(false);
                });
              } else {
                params.id = id;
                updateForm(params).then(() => {
                  message.success('修改成功！');
                  props.refresh();
                  setAddVisible(false);
                  setIsModalVisible(false);
                  setLoading(false);
                });
              }
            })
            .catch((errorInfo) => {});

          // setAddVisible(false);
        }}
        onCancel={() => setAddVisible(false)}
        className={styles.addForm}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          <Form.Item
            label="目录层级"
            name="directoryLevel"
            rules={[{ required: true, message: '请选择目录层级' }]}
          >
            <Radio.Group
              onChange={(e) => {
                setLevel(e.target.value);
              }}
            >
              <Radio value="type">一级目录/类型</Radio>
              <Radio value="form">二级目录/表单</Radio>
            </Radio.Group>
          </Form.Item>
          {level === 'type' && (
            <>
              <Form.Item
                label="分类名称"
                name="categoryName"
                rules={[{ required: true, message: '请输入分类名称' }]}
              >
                <Input placeholder="请输入分类名称" />
              </Form.Item>
            </>
          )}
          {level === 'form' && (
            <>
              <Form.Item
                label="归属分类"
                name="category"
                rules={[{ required: true, message: '请选择归属分类' }]}
              >
                <Select options={firstLevel} placeholder="请选择归属分类" />
              </Form.Item>
              <Form.Item
                label="表单名称"
                name="formName"
                rules={[{ required: true, message: '请输入表单名称' }]}
              >
                <Input placeholder="请输入表单名称" />
              </Form.Item>
              <Form.Item
                label="图标URL"
                name="iconUrl"
                rules={[{ required: true, message: '请输入图标URL' }]}
              >
                <Input placeholder="请输入图标URL" />
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>
    </>
  );
};

export default ConfigForm;
